﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Audit_Configuration_Oracle.Controllers;

namespace Audit_Configuration_Oracle.Views
{
    public partial class ACO_Audit_Rules : Form
    {
        bool isObject = false;
        int columnHeight = 0;
        int selectedIndex = 0;

        public ACO_Audit_Rules()
        {
            InitializeComponent();
        }

        private void ACO_Audit_Rules_Load(object sender, EventArgs e)
        {
            this.loadComboModalities();
        }

        private void loadComboModalities()
        {
            List<Dictionary<string, string>> modalities = null;
            Dictionary<string, string> record;
            this.cboModality.Items.Clear();

            try
            {
                modalities = AuditRulesController.GetAuditModalities();
                if (modalities != null && modalities.Count > 0)
                {
                    for (int i = 0; i < modalities.Count; i++)
                    {
                        record = modalities[i];
                        cboModality.Items.Add(new ComboBoxItem()
                        {
                            Text = record["text"],
                            Value = record["value"]
                        });
                    }

                    //cboModality.SelectedIndex = 0;
                    cboModality.SelectedIndex = (selectedIndex > modalities.Count - 1) ? modalities.Count - 1 : selectedIndex;
                    cboModality.Enabled = true;
                    lblMessage.Visible = false;
                }
                else
                {
                    cboModality.Enabled = false;
                    lblMessage.Visible = true;
                    selectedIndex = 0;
                }
            }
            catch (Exception error)
            {
                MessageBox.Show(error.Message);
             //   MessageBox.Show("Ocurrió un error cargando las modalidades disponibles", "Error",
               //     MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }
        }

        private void cboModality_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataSet ds = null;
            try
            {
                selectedIndex = cboModality.SelectedIndex;
                ComboBoxItem selected = (ComboBoxItem)cboModality.SelectedItem;
                if (selected.Text.ToUpper() == "OBJETOS")
                {
                    isObject = true;
                }
                else
                {
                    isObject = false;
                }
                ds = AuditRulesController.GetActiveRules(selected.Text, "");
                this.grdRules.DataSource = ds.Tables[0];
                                      

                if (columnHeight == 0)
                {
                    columnHeight = this.grdRules.ColumnHeadersHeight;
                }
            }
            catch (Exception error)
            {
                MessageBox.Show("Error recuperando las reglas de auditoría activas", 
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
            }

            this.grdRules.ColumnHeadersHeight = (columnHeight != 0) ? columnHeight : this.grdRules.ColumnHeadersHeight;

            if (isObject)
            {                
                for (int j = 0; j < this.grdRules.ColumnCount; j++)
                {
                    this.grdRules.Columns[j].Width = 45;
                }              

                this.grdRules.ColumnHeadersHeightSizeMode =
                     DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
                this.grdRules.ColumnHeadersHeight =
                            (this.grdRules.ColumnHeadersHeight) * 2;
                this.grdRules.ColumnHeadersDefaultCellStyle.Alignment =
                     DataGridViewContentAlignment.BottomCenter;
                this.grdRules.CellPainting += new
                     DataGridViewCellPaintingEventHandler(grdRules_CellPainting);
                this.grdRules.Paint += new PaintEventHandler(grdRules_Paint);

                for (int j = 4; j < this.grdRules.ColumnCount; j+=2)
                {
                    this.grdRules.Columns[j].HeaderText = "SUCCESS";
                    this.grdRules.Columns[j+1].HeaderText = "FAILURE";
                    this.grdRules.Columns[j].Width = 30;
                    this.grdRules.Columns[j + 1].Width = 30;
                }

                this.grdRules.Columns[grdRules.Columns.Count - 1].Width = this.grdRules.Columns[grdRules.Columns.Count - 2].Width;
            }
            else
            {
                this.grdRules.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;                
            }

            try
            {
                this.grdRules.Columns[0].Width = 55;
                this.grdRules.Columns[0].HeaderText = "";
            }
            catch { }
        }

        void grdRules_Paint(object sender, PaintEventArgs e)
        {
            if (isObject)
            {
                string[] types = { "", "", "SELECT", "INSERT", "UPDATE", "DELETE" };
                //this.grdRules.Columns[grdRules.Columns.Count - 1].MinimumWidth = this.grdRules.Columns[grdRules.Columns.Count - 3].Width;
                for (int j = 4; j < 12; )
                {
                    //get the column header cell
                    Rectangle r1 = this.grdRules.GetCellDisplayRectangle(j, -1, true);

                    r1.X += 1;
                    r1.Y += 1;
                    r1.Width = r1.Width * 2 - 2;
                    r1.Height = r1.Height / 2 - 2;
                    e.Graphics.FillRectangle(new SolidBrush(this.grdRules.ColumnHeadersDefaultCellStyle.BackColor), r1);
                    StringFormat format = new StringFormat();
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Center;
                    e.Graphics.DrawString(types[j / 2],
                        this.grdRules.ColumnHeadersDefaultCellStyle.Font,
                        new SolidBrush(this.grdRules.ColumnHeadersDefaultCellStyle.ForeColor),
                        r1,
                        format);
                    j += 2;
                }                
            }
            
        }

        void grdRules_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (isObject)
            {
                if (e.RowIndex == -1 && e.ColumnIndex > -1)
                {
                    e.PaintBackground(e.CellBounds, false);

                    Rectangle r2 = e.CellBounds;
                    r2.Y += e.CellBounds.Height / 2;
                    r2.Height = e.CellBounds.Height / 2;
                    e.PaintContent(r2);
                    e.Handled = true;
                }
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {            
            List<DataGridViewRow> rows_checked = new List<DataGridViewRow>();
            bool result = false;

            DialogResult dr = MessageBox.Show("¿Está seguro que desea desactivar la(s) regla(s) de auditoría seleccionada(s)?",
                "Advertencia",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (dr.Equals(DialogResult.Yes))
            {
                //gets selected rows
                foreach (DataGridViewRow row in grdRules.Rows)
                {
                    if (Convert.ToBoolean(row.Cells[0].Value))
                    {
                        rows_checked.Add(row);
                    }
                }
                result = AuditRulesController.DeactiveAuditRules(rows_checked);

                if (result)
                {
                    MessageBox.Show("Transaccion Exitosa", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Transaccion Fallida", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            this.btnDelete.Enabled = false;
            this.reloadAllControls();
        }

        private void grdRules_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (this.grdRules.IsCurrentCellDirty)
            {
                this.grdRules.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        private void grdRules_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                List<DataGridViewRow> rows_checked = getRowsChecked(e.ColumnIndex);

                if (rows_checked.Count > 0)
                {
                    btnDelete.Enabled = true;
                }
                else
                {
                    btnDelete.Enabled = false;
                }
            }
        }

        private List<DataGridViewRow> getRowsChecked(int cell)
        {
            List<DataGridViewRow> rows_checked = new List<DataGridViewRow>();
            bool valueCheck = false;

            foreach (DataGridViewRow row in grdRules.Rows)
            {
                if (cell == 0)
                {
                    valueCheck = Convert.ToBoolean(row.Cells[cell].AccessibilityObject.State.HasFlag(AccessibleStates.Checked));
                    if (valueCheck)
                    {
                        rows_checked.Add(row);
                    }
                }
            }

            return rows_checked;
        }

        private void grdRules_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (isObject)
            {
                ACO_Audit_Rules_Delete deleteForm =
                    new ACO_Audit_Rules_Delete(RowData(e.RowIndex), 4);

                //deleteForm.MdiParent = this.MdiParent;
                deleteForm.ShowDialog();
                this.reloadAllControls();
            }
        }

        public void reloadAllControls()
        {
            DataSet source = AuditRulesController.GetActiveRules(cboModality.Text, "");
            if (source != null)
            {
                this.grdRules.DataSource = source.Tables[0];
            }
            
            this.loadComboModalities();
        }

        private List<Dictionary<string, string>> RowData(int rowIndex)
        {
            List<Dictionary<string, string>> res = new List<Dictionary<string, string>>();
            Dictionary<string, string> data = null;
            DataGridViewRow row = grdRules.Rows[rowIndex];
            DataGridViewCell cell = null;

            for(int i = 0; i < row.Cells.Count; i++)
            {
                cell = row.Cells[i];
                data = new Dictionary<string,string>();
               
                data.Add("column", grdRules.Columns[cell.ColumnIndex].Name);
                data.Add("value", cell.Value.ToString());
                res.Add(data);
            }
            return res;
        }

        private void resetAllControls()
        {
            if (cboModality.Items.Count > 0)
            {
                cboModality.SelectedIndex = 0;
            }
        }

        private void ACO_Audit_Rules_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
            resetAllControls();
        }
        
    }

    public class ComboBoxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }

        public override string ToString()
        {
            return Text;
        }
    }
}
